package com.smart.common.smart;

import org.springframework.core.Ordered;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @author arnold.zhao
 * @date 2018/1/6 17:12
 */
public class SmartViewResolver implements ViewResolver,Ordered {
    //private static KbLogger LOGGER = KbLoggerFactory.getLogger(KbsViewResolver.class);

    private int order = 0;
    Map<String, ViewResolver> viewResolvers = new HashMap<String, ViewResolver>();

    /**
     * @param viewName
     * @param locale
     * @return
     * @throws Exception
     */
    public View resolveViewName(String viewName, Locale locale) throws Exception {
        // 对404的处理
        if("404".equals(viewName)){
            viewName =  "../global/404";
        }

        // 对500的处理
        if("500".equals(viewName)){
            viewName =  "../global/500";
        }

        /* 表示使用StringUtils的getFilenameExtension方法表示获取指定路径下的文件后缀；然后判断当前后缀是否是html或jsp，
         其实就是根据当前所给的字符串中的字符获取后缀名称，看源码即可*/

       String viewExtension = StringUtils.getFilenameExtension(viewName);

        /* 默认视图解析器，（当前所要解析的视图地址(名称)中不包含.html||.jsp时，则默认为映射路径为.html的模板引擎）,如果有.jsp的指定类型，
        则使用指定的jsp模板引擎进行解析；如：此时某一个Controller方法所return""的映射内容为，return "base/index";则此时则映射后直接指向到base/index.html文件
        并解析等处理后返回给浏览器，但如果此时return的内容是return "base/index.jsp"则此时则映射指向地址为 base/index.jsp的路径进行返回；
        */

        if (StringUtils.isEmpty(viewExtension)) {
            viewExtension = "html";
        }

        // 视图解析器
        ViewResolver viewResolver = viewResolvers.get(viewExtension);
        if (viewResolver != null) {
            View view = viewResolver.resolveViewName(viewName, locale);
            //LOGGER.debug("Returning [" + view + "] based on view extension '" + viewExtension + "'");

            return view;
        }
        //LOGGER.warn("No view found with view extension[" + viewExtension + "]; returning null");
        return null;
    }

    public int getOrder() {
        return order;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    public Map<String, ViewResolver> getViewResolvers() {
        return viewResolvers;
    }

    public void setViewResolvers(Map<String, ViewResolver> viewResolvers) {
        this.viewResolvers = viewResolvers;
    }
}
